<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊天存储系统测试</title>
    <style>
        body {
            font-family: 'Courier New', monospace;
            background: #1a1a1a;
            color: #ffffff;
            margin: 0;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
        }
        
        .test-section {
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid #666;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
        }
        
        .test-section h3 {
            color: #4CAF50;
            margin-top: 0;
        }
        
        button {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
            font-family: inherit;
        }
        
        button:hover {
            background: #45a049;
        }
        
        button:disabled {
            background: #666;
            cursor: not-allowed;
        }
        
        .output {
            background: #000;
            border: 1px solid #666;
            border-radius: 4px;
            padding: 10px;
            margin: 10px 0;
            min-height: 100px;
            overflow-y: auto;
            white-space: pre-wrap;
            font-size: 12px;
        }
        
        .success {
            color: #4CAF50;
        }
        
        .error {
            color: #f44336;
        }
        
        .info {
            color: #2196F3;
        }
        
        input[type="text"] {
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid #666;
            border-radius: 4px;
            color: white;
            padding: 8px;
            margin: 5px;
            font-family: inherit;
        }
        
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
            margin: 10px 0;
        }
        
        .stat-item {
            background: rgba(255, 255, 255, 0.05);
            padding: 10px;
            border-radius: 4px;
            text-align: center;
        }
        
        .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #4CAF50;
        }
        
        .stat-label {
            font-size: 12px;
            color: #ccc;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>聊天存储系统测试</h1>
        <p>测试 ChatStorage 类的各项功能，包括消息保存、加载、清理等。</p>
        
        <div class="test-section">
            <h3>基础功能测试</h3>
            <button onclick="testInitialization()">初始化存储</button>
            <button onclick="testSaveMessage()">保存测试消息</button>
            <button onclick="testLoadHistory()">加载历史记录</button>
            <button onclick="testAutoCleanup()">测试自动清理</button>
            <div class="output" id="basicOutput"></div>
        </div>
        
        <div class="test-section">
            <h3>消息管理测试</h3>
            <input type="text" id="messageInput" placeholder="输入测试消息" value="你好，我是玩家">
            <select id="entitySelect">
                <option value="cow">牛</option>
                <option value="pig">猪</option>
                <option value="sheep">羊</option>
                <option value="zombie">僵尸</option>
                <option value="skeleton">骷髅</option>
            </select>
            <button onclick="addTestMessage()">添加消息</button>
            <button onclick="loadEntityHistory()">加载实体历史</button>
            <button onclick="clearEntityHistory()">清除实体历史</button>
            <div class="output" id="messageOutput"></div>
        </div>
        
        <div class="test-section">
            <h3>存储统计信息</h3>
            <button onclick="updateStats()">更新统计</button>
            <button onclick="checkStorageHealth()">检查存储健康</button>
            <div class="stats" id="statsContainer">
                <div class="stat-item">
                    <div class="stat-value" id="totalMessages">0</div>
                    <div class="stat-label">总消息数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="storageSize">0</div>
                    <div class="stat-label">存储大小 (字节)</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="entityCount">0</div>
                    <div class="stat-label">实体数量</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="unreadCount">0</div>
                    <div class="stat-label">未读消息</div>
                </div>
            </div>
            <div class="output" id="statsOutput"></div>
        </div>
        
        <div class="test-section">
            <h3>数据导入导出</h3>
            <button onclick="exportData()">导出数据</button>
            <button onclick="importData()">导入数据</button>
            <button onclick="clearAllData()">清除所有数据</button>
            <div class="output" id="dataOutput"></div>
        </div>
        
        <div class="test-section">
            <h3>性能测试</h3>
            <button onclick="performanceTest()">批量消息测试</button>
            <button onclick="stressTest()">压力测试</button>
            <div class="output" id="performanceOutput"></div>
        </div>
    </div>

    <script type="module">
        import { ChatStorage } from './src/chat/ChatStorage.js';
        
        // 全局变量
        window.chatStorage = new ChatStorage();
        window.testEntityId = 'test_entity_1';
        
        // 工具函数
        function log(elementId, message, type = 'info') {
            const output = document.getElementById(elementId);
            const timestamp = new Date().toLocaleTimeString();
            const className = type === 'error' ? 'error' : type === 'success' ? 'success' : 'info';
            output.innerHTML += `<span class="${className}">[${timestamp}] ${message}</span>\n`;
            output.scrollTop = output.scrollHeight;
        }
        
        function clearOutput(elementId) {
            document.getElementById(elementId).innerHTML = '';
        }
        
        // 基础功能测试
        window.testInitialization = async function() {
            clearOutput('basicOutput');
            try {
                log('basicOutput', '开始初始化存储系统...', 'info');
                await window.chatStorage.initialize();
                log('basicOutput', '存储系统初始化成功！', 'success');
            } catch (error) {
                log('basicOutput', `初始化失败: ${error.message}`, 'error');
            }
        };
        
        window.testSaveMessage = async function() {
            try {
                const message = {
                    id: `msg_${Date.now()}`,
                    timestamp: Date.now(),
                    sender: 'player',
                    content: '这是一条测试消息',
                    entityId: window.testEntityId,
                    entityType: 'cow'
                };
                
                await window.chatStorage.saveMessage(message, {
                    messageType: 'conversation',
                    trigger: 'player_message',
                    importance: 'medium'
                });
                
                log('basicOutput', `消息保存成功: ${message.content}`, 'success');
            } catch (error) {
                log('basicOutput', `保存消息失败: ${error.message}`, 'error');
            }
        };
        
        window.testLoadHistory = async function() {
            try {
                const history = await window.chatStorage.loadHistory();
                log('basicOutput', `加载到 ${history.length} 条历史消息`, 'success');
                
                if (history.length > 0) {
                    const latest = history[history.length - 1];
                    log('basicOutput', `最新消息: ${latest.content}`, 'info');
                }
            } catch (error) {
                log('basicOutput', `加载历史失败: ${error.message}`, 'error');
            }
        };
        
        window.testAutoCleanup = async function() {
            try {
                await window.chatStorage.performAutoCleanup();
                log('basicOutput', '自动清理完成', 'success');
            } catch (error) {
                log('basicOutput', `自动清理失败: ${error.message}`, 'error');
            }
        };
        
        // 消息管理测试
        window.addTestMessage = async function() {
            clearOutput('messageOutput');
            try {
                const messageInput = document.getElementById('messageInput');
                const entitySelect = document.getElementById('entitySelect');
                
                const message = {
                    id: `msg_${Date.now()}`,
                    timestamp: Date.now(),
                    sender: Math.random() > 0.5 ? 'player' : 'entity',
                    content: messageInput.value || '测试消息',
                    entityId: `${entitySelect.value}_1`,
                    entityType: entitySelect.value
                };
                
                await window.chatStorage.saveMessage(message, {
                    messageType: 'conversation',
                    trigger: 'player_message',
                    gameContext: {
                        playerPosition: { x: 0, y: 64, z: 0 },
                        timeOfDay: 'noon',
                        weather: 'clear'
                    },
                    importance: 'medium'
                });
                
                log('messageOutput', `消息已添加: [${message.sender}] ${message.content}`, 'success');
            } catch (error) {
                log('messageOutput', `添加消息失败: ${error.message}`, 'error');
            }
        };
        
        window.loadEntityHistory = async function() {
            try {
                const entitySelect = document.getElementById('entitySelect');
                const entityId = `${entitySelect.value}_1`;
                const entityType = entitySelect.value;
                
                const history = await window.chatStorage.loadHistory(entityId, entityType);
                log('messageOutput', `${entityType} 的历史记录 (${history.length} 条):`, 'info');
                
                history.forEach((msg, index) => {
                    const time = new Date(msg.timestamp).toLocaleTimeString();
                    log('messageOutput', `${index + 1}. [${time}] ${msg.sender}: ${msg.content}`, 'info');
                });
            } catch (error) {
                log('messageOutput', `加载实体历史失败: ${error.message}`, 'error');
            }
        };
        
        window.clearEntityHistory = async function() {
            try {
                const entitySelect = document.getElementById('entitySelect');
                const entityId = `${entitySelect.value}_1`;
                const entityType = entitySelect.value;
                
                await window.chatStorage.clearEntityHistory(entityId, entityType);
                log('messageOutput', `${entityType} 的历史记录已清除`, 'success');
            } catch (error) {
                log('messageOutput', `清除实体历史失败: ${error.message}`, 'error');
            }
        };
        
        // 统计信息
        window.updateStats = function() {
            clearOutput('statsOutput');
            try {
                const stats = window.chatStorage.getStorageStats();
                
                document.getElementById('totalMessages').textContent = stats.totalMessages;
                document.getElementById('storageSize').textContent = stats.storageSize;
                document.getElementById('entityCount').textContent = Object.keys(stats.messagesByEntity).length;
                document.getElementById('unreadCount').textContent = window.chatStorage.getUnreadCount();
                
                log('statsOutput', '统计信息已更新', 'success');
                log('statsOutput', `实体消息分布: ${JSON.stringify(stats.messagesByEntity, null, 2)}`, 'info');
                
                if (stats.totalMessages > 0) {
                    const oldestTime = new Date(stats.oldestMessage).toLocaleString();
                    const newestTime = new Date(stats.newestMessage).toLocaleString();
                    log('statsOutput', `最旧消息: ${oldestTime}`, 'info');
                    log('statsOutput', `最新消息: ${newestTime}`, 'info');
                }
            } catch (error) {
                log('statsOutput', `更新统计失败: ${error.message}`, 'error');
            }
        };
        
        window.checkStorageHealth = async function() {
            try {
                const isHealthy = await window.chatStorage.checkStorageHealth();
                const status = isHealthy ? '健康' : '异常';
                const type = isHealthy ? 'success' : 'error';
                log('statsOutput', `存储健康状态: ${status}`, type);
            } catch (error) {
                log('statsOutput', `健康检查失败: ${error.message}`, 'error');
            }
        };
        
        // 数据导入导出
        window.exportData = async function() {
            clearOutput('dataOutput');
            try {
                const exportedData = await window.chatStorage.exportHistory();
                log('dataOutput', '数据导出成功', 'success');
                log('dataOutput', `导出数据大小: ${exportedData.length} 字符`, 'info');
                
                // 创建下载链接
                const blob = new Blob([exportedData], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `chat_history_${new Date().toISOString().split('T')[0]}.json`;
                a.click();
                URL.revokeObjectURL(url);
                
                log('dataOutput', '导出文件已下载', 'success');
            } catch (error) {
                log('dataOutput', `导出失败: ${error.message}`, 'error');
            }
        };
        
        window.importData = function() {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = '.json';
            input.onchange = async function(e) {
                const file = e.target.files[0];
                if (!file) return;
                
                try {
                    const text = await file.text();
                    await window.chatStorage.importHistory(text);
                    log('dataOutput', '数据导入成功', 'success');
                    updateStats();
                } catch (error) {
                    log('dataOutput', `导入失败: ${error.message}`, 'error');
                }
            };
            input.click();
        };
        
        window.clearAllData = async function() {
            if (!confirm('确定要清除所有聊天数据吗？此操作不可恢复！')) {
                return;
            }
            
            try {
                await window.chatStorage.clearAllHistory();
                log('dataOutput', '所有数据已清除', 'success');
                updateStats();
            } catch (error) {
                log('dataOutput', `清除数据失败: ${error.message}`, 'error');
            }
        };
        
        // 性能测试
        window.performanceTest = async function() {
            clearOutput('performanceOutput');
            const messageCount = 100;
            
            try {
                log('performanceOutput', `开始批量添加 ${messageCount} 条消息...`, 'info');
                const startTime = performance.now();
                
                for (let i = 0; i < messageCount; i++) {
                    const message = {
                        id: `perf_msg_${i}`,
                        timestamp: Date.now() + i,
                        sender: i % 2 === 0 ? 'player' : 'entity',
                        content: `性能测试消息 #${i}`,
                        entityId: `perf_entity_${i % 5}`,
                        entityType: ['cow', 'pig', 'sheep', 'zombie', 'skeleton'][i % 5]
                    };
                    
                    await window.chatStorage.saveMessage(message, {
                        messageType: 'conversation',
                        importance: 'low'
                    });
                }
                
                const endTime = performance.now();
                const duration = endTime - startTime;
                
                log('performanceOutput', `批量添加完成！`, 'success');
                log('performanceOutput', `总耗时: ${duration.toFixed(2)}ms`, 'info');
                log('performanceOutput', `平均每条消息: ${(duration / messageCount).toFixed(2)}ms`, 'info');
                
                updateStats();
            } catch (error) {
                log('performanceOutput', `性能测试失败: ${error.message}`, 'error');
            }
        };
        
        window.stressTest = async function() {
            clearOutput('performanceOutput');
            
            try {
                log('performanceOutput', '开始压力测试...', 'info');
                
                // 测试大量消息的加载性能
                const loadStartTime = performance.now();
                const allHistory = await window.chatStorage.loadHistory();
                const loadEndTime = performance.now();
                
                log('performanceOutput', `加载 ${allHistory.length} 条消息耗时: ${(loadEndTime - loadStartTime).toFixed(2)}ms`, 'info');
                
                // 测试自动清理性能
                const cleanupStartTime = performance.now();
                await window.chatStorage.performAutoCleanup();
                const cleanupEndTime = performance.now();
                
                log('performanceOutput', `自动清理耗时: ${(cleanupEndTime - cleanupStartTime).toFixed(2)}ms`, 'info');
                
                // 测试存储健康检查
                const healthStartTime = performance.now();
                const isHealthy = await window.chatStorage.checkStorageHealth();
                const healthEndTime = performance.now();
                
                log('performanceOutput', `健康检查耗时: ${(healthEndTime - healthStartTime).toFixed(2)}ms`, 'info');
                log('performanceOutput', `存储状态: ${isHealthy ? '健康' : '异常'}`, isHealthy ? 'success' : 'error');
                
                log('performanceOutput', '压力测试完成！', 'success');
            } catch (error) {
                log('performanceOutput', `压力测试失败: ${error.message}`, 'error');
            }
        };
        
        // 页面加载时自动初始化
        window.addEventListener('load', async function() {
            await testInitialization();
            updateStats();
        });
    </script>
</body>
</html>